<template>
  <div>
    <a-button  v-if="!$route.query.id" type="primary" @click="showModal('add')" style="margin-bottom: 16px;">
      新增
    </a-button>
    <a-table
      :columns="columns"
      :dataSource="data"
      :rowKey="record => record.id"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template slot="operation" slot-scope="text, record">
        <a-button type="link" @click="showModal('view', record)">查看</a-button>
        <a-button type="link" @click="go(record)">扫描件查看管理</a-button>
        <a-button type="link" @click="showModal('edit', record)">编辑</a-button>
        <a-popconfirm title="确定删除这条记录吗？" @confirm="() => handleDelete(record.id)" okText="是" cancelText="否">
          <a-button type="link">删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>

    <a-modal :title="modalTitle" :visible="modalVisible" @ok="handleModalOk" @cancel="handleModalCancel" :width="800">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :span="12" v-for="field in formFields" :key="field.name">
            <a-form-model-item :label="field.label" :prop="field.name">
              <component
                :is="getComponentType(field.type)"
                v-model="form[field.name]"
                :disabled="modalMode === 'view'"
                v-bind="getComponentProps(field)"
              >
                <!--                  <a-tree-select
                    v-model="form.legalNature"
                    :disabled="!canFix"
                    show-search
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择供应商/投标人/受让方性质"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="treeData['A02']"
                  >
                  </a-tree-select>-->
                <!--                  <j-area-linkage v-model="form.regionCode" type="cascader" :disabled="!canFix" />-->
                <template v-if="field.type === 'select'" v-for="option in getListOpt(field.options)">
                  <a-select-option :key="option.value" :value="option.value">
                    {{ option.label }}
                  </a-select-option>
                </template>
              </component>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" @click="handleModalCancel">取消</a-button>
        <a-button key="fillRandom" @click="fillRandomValues" :disabled="modalMode === 'view'">
          填充随机值
        </a-button>
        <a-button key="submit" type="primary" @click="handleModalOk" :loading="confirmLoading">
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { formFields2 as formFields } from '../utils/formFields'
import { getRandomValue } from '../utils/randomValueGenerator'
import moment from 'moment'
import { assignKeyToValue } from '@views/user/register/reg_components/step2.vue'
import { getComponentType } from '../utils/formFields'
export default {
  props: {
    user: {
      type: Object,
    },
  },
  data() {
    return {
      columns: [
        { title: '姓名', dataIndex: 'name', key: 'name' },
        { title: '身份证号', dataIndex: 'cardCode', key: 'cardCode' },
        { title: '手机号码', dataIndex: 'phone', key: 'phone' },
        { title: '性别', dataIndex: 'sex', key: 'sex' },
        { title: '出生日期', dataIndex: 'birthDay', key: 'birthDay' },
        { title: '学历', dataIndex: 'xl', key: 'xl' },
        { title: '职称', dataIndex: 'zc', key: 'zc' },
        { title: '所属部门', dataIndex: 'department', key: 'department' },
        { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' } },
      ],
      data: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      modalVisible: false,
      modalTitle: '',
      modalMode: '',
      confirmLoading: false,
      form: {},
      rules: {},
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      formFields: formFields,
      opt: {},
      treeData: {},
    }
  },

  methods: {
    getComponentType,
    getTree(userType) {
      this.$http.get('/register/common/loadTreeRoot', { params: userType }).then(r => {
        // console.log(r.result)
        assignKeyToValue(r.result)
        // console.log(r.result)
        /* this.treeData = r.result*/
        this.$set(this.treeData, userType.pcode, r.result)
      })
    },
    getListOpt(url) {
      if (url && typeof url === 'string') {
        return this.opt[url]
      }
      return url
    },
    getOptions(url) {
      if (url && typeof url === 'string') {
        this.$http.get('/register/common/getDictItems/' + url).then(v => {
          console.log(v)
          this.opt[url] = v.result.map(item => {
            return {
              ...item,
              value: item.value,
              label: item.text,
            }
          })
        })
      }
    },
    go(record) {
      this.$router.push({ path: '/filelist-view', query: { type: 2, employeeId: record.id } })
    },
    handleTableChange(pagination) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.fetchData()
    },
    fetchData() {
      // Implement API call to fetch data
      // For demonstration, we'll use mock data
      this.$http
        .get('/register/agencyLegalEmployees/list', {
          params: {
            legalCode: this.user.legalCode,
            pageNo: this.pagination.current,
            pageSize: this.pagination.pageSize,
          },
        })
        .then(r => {
          this.data = r.result.records
          this.pagination.total = r.result.total
        })

    },
    showModal(mode, record = null) {
      this.modalMode = mode
      this.modalTitle = mode === 'add' ? '新增' : mode === 'edit' ? '编辑' : '查看'
      this.modalVisible = true
      if (record) {
        this.form = { ...record }
      } else {
        this.initForm()
      }
    },
    handleModalOk() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          // Implement API call to save data

          this.formFields.forEach(field => {
            if (field.type === 'string(date-time)') {
              this.$set(
                this.form,
                field.name,
                this.form[field.name] ? moment(this.form[field.name]).format('YYYY-MM-DD') : '',
              )
            }
          })

          this.$http
            .post('/register/agencyLegalEmployees/' + (this.form.id ? 'edit' : 'add'), {
              legalCode: this.user.legalCode,
              ...this.form,
            })
            .then(r => {
              this.modalVisible = false
              this.confirmLoading = false
              this.fetchData() // Refresh data after save
            })
            .catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleModalCancel() {
      this.modalVisible = false
      this.confirmLoading = false
    },
    handleDelete(id) {
      deleteAction('/register/agencyLegalEmployees/delete', { id }).then(r => {
        this.fetchData()
        this.$message.success('删除成功')
      })
    },
    initForm() {
      this.form = {}
      this.formFields.forEach(field => {
        this.$set(this.form, field.name, '')
      })
    },

    getComponentProps(field) {
      switch (field.type) {
        case 'string(date-time)':
          return {
            format: 'YYYY-MM-DD',
            showTime: false,
            valueformat: (date, format) => {
              return moment(date).format('YYYY-MM-DD')
            },
            style: { width: '100%' },
          }
        case 'integer(int64)':
          return { style: { width: '100%' } }
        case 'j-area-linkage':
          return { type: 'cascader' }
        case 'a-tree-select':
          return {
            'show-search': true,
            style: 'width: 100%',
            'dropdown-style': { maxHeight: '400px', overflow: 'auto' },
            placeholder: '请选择',
            'llow-clear': true,
            'tree-default-expand-all': true,
            'tree-data': this.treeData['A08'],
          }
        default:
          return {}
      }
    },
    fillRandomValues() {
      this.formFields.forEach(field => {
        this.$set(this.form, field.name, getRandomValue(field))
      })
    },
  },
  created() {
    this.getTree({ async: false, pcode: 'A08' })
    this.getOptions('card_type')
    this.fetchData()
  },
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 0;
}
</style>
